package com.ruoyi.cs.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.banbeiPay.Disguiser;
import com.ruoyi.common.banbeiPay.HttpClientService;
import com.ruoyi.common.banbeiPay.MyBeanUtils;
import com.ruoyi.common.banbeiPay.MyDateUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.TransferQueryReqParam;
import com.ruoyi.common.utils.bean.TransferQueryResParam;
import com.ruoyi.common.utils.bean.TransferReqParam;
import com.ruoyi.common.utils.bean.TransferResParam;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.cs.domain.TBankcardBehalfpay;
import com.ruoyi.cs.mapper.TBankcardBehalfpayMapper;
import com.ruoyi.cs.service.CommonService;
import com.ruoyi.cs.service.ITBankcardBehalfpayService;
import org.apache.commons.httpclient.HttpStatus;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.text.Convert;

/**
 * 银行卡代付信息Service业务层处理
 * 
 * @author liuhongbin
 * @date 2022-08-31
 */
@Service
@SuppressWarnings("ALL")
public class TBankcardBehalfpayServiceImpl implements ITBankcardBehalfpayService
{
    @Autowired
    private TBankcardBehalfpayMapper tBankcardBehalfpayMapper;

    @Autowired
    private CommonService commonService;

    private final  static Logger log = LoggerFactory.getLogger(TBankcardBehalfpayServiceImpl.class);

    /**
     * 查询银行卡代付信息
     * 
     * @param orderId 银行卡代付信息ID
     * @return 银行卡代付信息
     */
    @Override
    public TBankcardBehalfpay selectTBankcardBehalfpayById(String orderId)
    {
        return tBankcardBehalfpayMapper.selectTBankcardBehalfpayById(orderId);
    }

    /**
     * 查询银行卡代付信息列表
     * 
     * @param tBankcardBehalfpay 银行卡代付信息
     * @return 银行卡代付信息
     */
    @Override
    public List<TBankcardBehalfpay> selectTBankcardBehalfpayList(TBankcardBehalfpay tBankcardBehalfpay)
    {
        return tBankcardBehalfpayMapper.selectTBankcardBehalfpayList(tBankcardBehalfpay);
    }

    /**
     * 新增银行卡代付信息
     * 
     * @param tBankcardBehalfpay 银行卡代付信息
     * @return 结果
     */
    @Override
    public Response<String> insertTBankcardBehalfpay(String amount)
    {
        TBankcardBehalfpay tBankcardBehalfpay = new TBankcardBehalfpay();
        String orderId =  DateUtils.dateTimeNow() + IdUtils.fastUUID().substring(0, 8);
        Map<String, Object> resultMap = null;
        try {
            TransferReqParam param = commonService.createTransferReqParam(orderId,amount);
            Map<String, String> map = MyBeanUtils.convertBean(param, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, TransferReqParam.NEED_SIGN_PARAMS, true);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            resultMap = HttpClientService.getHttpResp(map, Constants.TRANSFER_URL);
            log.info("宝和利代付下单响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                TransferResParam resParam = JSONObject.parseObject(resultMsg, TransferResParam.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(resParam, TransferResParam.NEED_SIGN_PARAMS, true);
                String responseSign = resParam.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    final String rt3RetMsg = resParam.getRt3_retMsg();
                    if ("0000".equals(resParam.getRt2_retCode())) {
                        /**转换实体类*/
                        TBankcardBehalfpay bankcardBehalfpay = commonService.toTBankcardBehalfpayByTransferReqParam(resParam);
                        bankcardBehalfpay.setOrderId(orderId);
                        bankcardBehalfpay.setAmount(new BigDecimal(amount));
                        tBankcardBehalfpayMapper.insertTBankcardBehalfpay(bankcardBehalfpay);

                        log.info("宝和利代付下单下单成功");
                        return Response.success("宝和利代付下单成功");
                    } else {
                        log.error("宝和利代付下单返回失败", resParam.getRt5_orderId() + "-" + rt3RetMsg);
                        return Response.fail("宝和利代付下单返回失败:"+rt3RetMsg);
                    }
                } else {
                    log.error("宝和利代付验签失败", resultMsg);
                    return Response.fail("宝和利代付验签失败");
                }
            } else {
                log.error("宝和利代付下单请求失败:{}",resultMap);
                return Response.fail("宝和利代付下单请求失败!");
            }
        } catch (Exception e) {
            log.error("宝和利代付下单交易异常：{}" + e.getMessage());
            return Response.fail("宝和利代付下单交易异常："+e.getMessage());
        }
    }




    /**
     * 修改银行卡代付信息
     * 
     * @param tBankcardBehalfpay 银行卡代付信息
     * @return 结果
     */
    @Override
    public int updateTBankcardBehalfpay(TBankcardBehalfpay tBankcardBehalfpay)
    {
        return tBankcardBehalfpayMapper.updateTBankcardBehalfpay(tBankcardBehalfpay);
    }

    /**
     * 删除银行卡代付信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTBankcardBehalfpayByIds(String ids)
    {
        return tBankcardBehalfpayMapper.deleteTBankcardBehalfpayByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除银行卡代付信息信息
     * 
     * @param orderId 银行卡代付信息ID
     * @return 结果
     */
    @Override
    public int deleteTBankcardBehalfpayById(String orderId)
    {
        return tBankcardBehalfpayMapper.deleteTBankcardBehalfpayById(orderId);
    }

    /**
     * 宝和利代付查询
     * @param orderId
     * @return
     */
    @Override
    public Response<TBankcardBehalfpay> transferQuery(String orderId) {
        Map<String, Object> resultMap = null;
        try {
            TransferQueryReqParam param = commonService.createrTransferQueryReqParam(orderId);
            Map<String, String> map = MyBeanUtils.convertBean(param, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, TransferQueryReqParam.NEED_SIGN_PARAMS, true);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            resultMap = HttpClientService.getHttpResp(map, Constants.TRANSFER_URL);
            log.info("宝和利代付查询响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                TransferQueryResParam resParam = JSONObject.parseObject(resultMsg, TransferQueryResParam.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(resParam, TransferQueryResParam.NEED_SIGN_PARAMS, true);
                String responseSign = resParam.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    final String rt3RetMsg = resParam.getRt3_retMsg();
                    if ("0000".equals(resParam.getRt2_retCode())) {
                        log.info("宝和利代付查询成功");
                        TBankcardBehalfpay bankcardBehalfpay = commonService.toTBankcardBehalfpayByTransferQueryResParam(resParam);
                        return Response.success(bankcardBehalfpay);
                    } else {
                        log.error("宝和利代付查询返回失败", resParam.getRt5_orderId() + "-" + rt3RetMsg);
                        return Response.fail("宝和利代付查询返回失败:"+rt3RetMsg);
                    }
                } else {
                    log.error("宝和利代付查询验签失败:{}", resultMsg);
                    return Response.fail("宝和利代付查询验签失败");
                }
            } else {
                log.error("宝和利代付查询请求失败：{}", resultMap);
                return Response.fail("宝和利代付查询请求失败");

            }
        } catch (Exception e) {
            log.error("宝和利代付查询异常:{},返回数据:{}",e.getMessage(),resultMap);
            return Response.fail("宝和利代付查询异常:"+e.getMessage());
        }
    }

    @Override
    public void bhlbehalfpayHandle(TBankcardBehalfpay tBankcardBehalfpay) {
        Map<String, Object> resultMap = null;
        try {
            TransferQueryReqParam param = commonService.createrTransferQueryReqParam(tBankcardBehalfpay.getOrderId());
            Map<String, String> map = MyBeanUtils.convertBean(param, new LinkedHashMap());
            String oriMessage = MyBeanUtils.getSignedByPresetParameter(map, TransferQueryReqParam.NEED_SIGN_PARAMS, true);
            String sign = Disguiser.disguiseMD5(oriMessage.trim());
            map.put("sign", sign);
            resultMap = HttpClientService.getHttpResp(map, Constants.TRANSFER_URL);
            log.info("宝和利代付查询响应结果：" + resultMap);
            if ((Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                TransferQueryResParam resParam = JSONObject.parseObject(resultMsg, TransferQueryResParam.class);
                String assemblyRespOriSign = MyBeanUtils.getSignedByPresetParameter(resParam, TransferQueryResParam.NEED_SIGN_PARAMS, true);
                String responseSign = resParam.getSign();
                String checkSign = Disguiser.disguiseMD5(assemblyRespOriSign.trim());
                if (checkSign.equals(responseSign)) {
                    final String rt3RetMsg = resParam.getRt3_retMsg();
                    if ("0000".equals(resParam.getRt2_retCode())) {
                        log.info("宝和利代付查询成功:{}",resultMsg);
                        TBankcardBehalfpay bankcardBehalfpay = commonService.toTBankcardBehalfpayByTransferQueryResParam(resParam);
                        bankcardBehalfpay.setUpdateTime(DateUtils.getNowDate());
                        bankcardBehalfpay.setOrderId(tBankcardBehalfpay.getOrderId());
                        tBankcardBehalfpayMapper.updateTBankcardBehalfpay(bankcardBehalfpay);
                        log.info("宝和利代付订单更新成功:{}",bankcardBehalfpay.getOrderId());
                    } else {
                        log.error("宝和利代付查询返回失败", resParam.getRt5_orderId() + "-" + rt3RetMsg);
                    }
                } else {
                    log.error("宝和利代付查询验签失败:{}", resultMsg);
                }
            } else {
                log.error("宝和利代付查询请求失败：{}", resultMap);
            }
        } catch (Exception e) {
            log.error("宝和利代付查询异常:{},返回数据:{}",e.getMessage(),resultMap);
        }
    }

    @Override
    public List<TBankcardBehalfpay> selectTBankcardBehalfpayAll() {
        return tBankcardBehalfpayMapper.selectTBankcardBehalfpayAll();
    }

    @Override
    public Response<Map> transferCount() {
        return Response.success(tBankcardBehalfpayMapper.behalfpayCount());
    }

}
